const UserService = require('../../services/admin/UserService')
const JWT = require('../../utils/JWT')
const UserController = {
  login: async (req, res) => {
    // console.log(req.body)
    // req.body
    const result = await UserService.login(req.body)
    if (result.length === 0) {
      res.send({
        code: '-1',
        error: '用户名和密码不匹配'
      })
    } else {
      // 登录成功，生成 token 
      const token = JWT.generate({
        _id: result[0]._id,
        username: result[0].username,
      }, '1d')
      // 携带 token 传给前端，让前端可以存储 token
      res.header("Authorization", token)
      res.send({
        ActionType: 'OK',
        data: {
          username: result[0].username,
          gender: result[0].gender ? result[0].gender : 0,  // 性别  0 保密
          introduction: result[0].introduction,
          avatar: result[0].avatar,
          role: result[0].role  // 管理员 1 编辑 2
        }
      })
    }
  },
  upload: async (req, res) => {
    // console.log(req.body,req.file)
    const { username, introduction, gender } = req.body
    const token = req.headers['authorization'].split(' ')[1]
    const payload = JWT.verify(token)
    const avatar = req.file ? `/avataruploads/${req.file.filename}` : ''
    await UserService.upload({ _id: payload._id, username, introduction, gender: Number(gender), avatar })
    if (avatar) {
      res.send({
        ActionType: 'OK',
        data: {
          username,
          gender: Number(gender),
          introduction,
          avatar,
        }
      })
    } else {
      res.send({
        ActionType: 'OK',
        data: {
          username,
          gender: Number(gender),
          introduction,
        }
      })
    }
  },
  add: async (req, res) => {
    const { username, introduction, gender, role, password } = req.body
    const avatar = `/avataruploads/${req.file.filename}`
    await UserService.add({ username, introduction, gender: Number(gender), avatar, password, role: Number(role) })
    res.send({
      ActionType: 'OK',
    })
  },
  list: async (req, res) => {
    const userList = await UserService.list(req.params)
    res.send({
      ActionType: 'OK',
      data: userList
    })
  },
  delete: async (req, res) => {
    await UserService.delete({ _id: req.params.id })
    res.send({
      ActionType: 'OK'
    })
  },
  put: async (req, res) => {
    await UserService.put(req.body)
    res.send({
      ActionType: "OK"
    })
  }
}
module.exports = UserController